package yang.learn.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import yang.learn.entity.ChatRecord;
import yang.learn.service.ChatRecordService;

import java.util.List;

@Controller
@RequestMapping("/chat/record")
public class ChatRecordController {
    @Autowired(required = false)
    private ChatRecordService chatRecordService;

    @RequestMapping("/list")
     public String list(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        //服务端备份用户信息
        int user_id = Integer.parseInt(String.valueOf(session.getAttribute("user_id")));
        int contacts_id = Integer.parseInt(String.valueOf(session.getAttribute("contacts_id")));
        //查询用户发与联系人的信息
        List<ChatRecord> chatRecordList = chatRecordService.queryAll(
                new ChatRecord(user_id,contacts_id));
        System.out.println(user_id+"和"+contacts_id+"聊天记录"+chatRecordList);
        model.addAttribute("chatRecordList",chatRecordList);
        return "chat/record.html :: chat";
    }

    @RequestMapping("/add")
    public ModelAndView add(HttpServletRequest request,@RequestBody ChatRecord chatRecord){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("chatroom");
        HttpSession session = request.getSession();
        //服务端备份用户信息
        int user_id = Integer.parseInt(String.valueOf(session.getAttribute("user_id")));
        int contacts_id = Integer.parseInt(String.valueOf(session.getAttribute("contacts_id")));
        System.out.println("给联系人"+contacts_id+"消息内容"+chatRecord.getChat_context());
        String chat_name = String.valueOf(session.getAttribute("user_name"));
        chatRecordService.add(
                new ChatRecord(0,user_id,contacts_id,chat_name,chatRecord.getChat_context()));
        return modelAndView;
    }


}
